package databases

import (
	"GoServer/utils/config"
	"GoServer/utils/databases/mongodb"
	"GoServer/utils/debug"
	"context"
	"github.com/go-redis/redis/v8"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

var (
	SQLDB        *gorm.DB
	Rediss       *redis.Client
	MongDBClient *mongo.Client
	MongoDB      *mongo.Database
)

func InitDatabases() {
	initRedis()
	initMongdb()
}

func initRedis() {
	Rediss = redis.NewClient(&redis.Options{
		Addr:         config.GetConfig("app").GetString("redis.addr"),
		Password:     config.GetConfig("app").GetString("redis.password"),
		DB:           config.GetConfig("app").GetInt("redis.DB"),
		PoolSize:     config.GetConfig("app").GetInt("redis.poolSize"),
		MinIdleConns: config.GetConfig("app").GetInt("redis.minIdleConn"),
	})

	pong, err := Rediss.Ping(context.TODO()).Result()
	if err != nil {
		debug.Logln(debug.Error, "redis error : ", err)
	} else {
		debug.Logln(debug.Info, "redis inited success :", pong)
	}
}

func initMongdb() {
	uri := config.GetConfig("app").GetString("mongodb.uri")

	clientOptions := options.Client().ApplyURI(uri)

	MongDBClient, _ = mongo.Connect(context.Background(), clientOptions)

	err := MongDBClient.Ping(context.Background(), nil)
	if err != nil {
		debug.Logln(debug.Error, "Ping错误", err)
		return
	}

	dbname := config.GetConfig("app").GetString("mongodb.database")
	MongoDB = MongDBClient.Database(dbname)
	debug.Logln(debug.Info, "连接mongodb 数据库: ", dbname)
	debug.Logln(debug.Info, "Connected to MongoDB Success!!")

	mongodb.CreateIndexes(MongoDB)
}

func initMySQL() {
	newLogger := logger.New(
		debug.SqlWriter{},
		logger.Config{
			SlowThreshold: time.Second, // 慢SQL阈值
			LogLevel:      logger.Info, // 级别
			Colorful:      true,        /// 彩色
		},
	)

	SQLDB, _ = gorm.Open(mysql.Open(config.GetConfig("app").GetString("mysql.dsn")), &gorm.Config{
		Logger: newLogger,
	})

	maxIdleConns := config.GetConfig("app").GetInt("mysql.maxIdleConns")
	maxOpenConns := config.GetConfig("app").GetInt("mysql.maxOpenConns")
	connMaxLifetime := config.GetConfig("app").GetInt("mysql.connMaxLifetime")
	sqlDB, _ := SQLDB.DB()
	if sqlDB != nil {
		sqlDB.SetMaxIdleConns(maxIdleConns)                                    // 空闲连接数
		sqlDB.SetMaxOpenConns(maxOpenConns)                                    // 最大连接数
		sqlDB.SetConnMaxLifetime(time.Second * time.Duration(connMaxLifetime)) // 单位：秒
	}

	debug.Logln(debug.Info, "SQLDB inited !!!")
}
